<script lang="ts" setup>
import auth from '@/api/auth'
import mcht from '@/api/mcht'
import { useHomeStore, useAuthStore } from '@/store'

const messageTemplateId = import.meta.env.VITE_MESSAGE_TEMPLATE_ID

const authStore = useAuthStore()
const {
  userName,
  roleFlag,
  phoneNumber,
  msgSwitch,
} = storeToRefs(useHomeStore())
const menuList = [
  {
    name: '修改密码',
    // icon: '/static/home/1.png',
    icon: 'i-ri:lock-password-line',
    link: '/pages/my/modify',
    color: '#49b557', bgcolor: '#e5faec'
  },
  {
    name: '商户信息',
    // icon: '/static/home/1.png',
    icon: 'i-ri:user-search-line',
    link: '/pages/my/merchant/list',
    color: '#9e77b4', bgcolor: '#fce3fc'
  },
  {
    name: '意愿确认',
    // icon: '/static/home/4.png'
    icon: 'i-ri:question-line',
    color: '#f96566', bgcolor: '#fbe9e9'
  },
  {
    name: '关于',
    // icon: '/static/home/2.png',
    icon: 'i-ri:information-line',
    link: '/pages/my/about',
    color: '#548c82', bgcolor: '#daf5e7'
  },
  {
    name: '退出登录',
    // icon: '/static/home/3.png'
    icon: 'i-ri:login-circle-line',
    color: '#ac5663', bgcolor: '#fedad4'
  },
]

let menu = []
if (roleFlag.value === '00') {
  menu = menuList
} else {
  menu = menuList.filter(i => !['意愿确认'].includes(i.name))
}

const push = ref<boolean>(false)
if (msgSwitch.value === '1') {
  push.value = true
}


watch(() => push.value, async (value) => {
  if (value) {
    // 打开开关，调腾讯订阅接口
    wx.requestSubscribeMessage({
      tmplIds: [messageTemplateId],
      success: async (res) => {
        if (res.errMsg === 'requestSubscribeMessage:ok') {
          // 判断用户有未同意订阅
          const subscribeStatus = res[messageTemplateId]
          if ((/^accept/).test(subscribeStatus)) {
            // 同意订阅，调接口打开
            const { data } = await mcht.setPushSwitch({
              msgSwitch: value ? '1' : '0'
            })
            if (data.status === 'success') {
              uni.showToast({
                icon: 'success',
                title: data.message,
              })
            }
          } else if (subscribeStatus === 'reject') {
            // 未订阅，将开关重置为关闭
            push.value = false
            // 并弹框提醒用户
            uni.showModal({
              title: '拒绝推送提示',
              content: '您已设置不接收消息提醒，若要接收提醒消息，请手动点击右上角小程序菜单-设置-通知管理-收款到账通知里选择接收并开启语音提醒'
            })
          } else {
            // 未订阅，将开关重置为关闭
            push.value = false
          }
        }
      },
      fail() {
        push.value = false
      }
    })
  } else {
    // 关闭推送开关，正常调接口关闭即可
    const { data } = await mcht.setPushSwitch({
      msgSwitch: value ? '1' : '0'
    })
    if (data.status === 'success') {
      uni.showToast({
        icon: 'success',
        title: data.message,
      })
    }
  }
})


function goMenu(item) {
  if (item.name === '退出登录') {
    logout()
  } else if (item.name === '意愿确认') {
    visible.value = true
  } else {
    uni.navigateTo({
      url: item.link,
    })
  }
}
function logout() {
  uni.showModal({
    title: '退出登录确认',
    content: '您是否确认要退出登录？',
    success: async (res) => {
      if (res.confirm) {
        const { data } = await auth.logout(phoneNumber.value)
        if (data.status === 'success') {
          uni.showToast({
            icon: 'success',
            title: data.message
          })
          authStore.logout()
          uni.reLaunch({
            url: '/pages/index/index'
          })
        }
      }
    },
  })
}
const visible = ref<boolean>(false)
const menuItems = [
  {
    name: '微信',
    value: 'wx'
  },
  {
    name: '支付宝',
    value: 'alipay'
  }
]

function chooseItem(item: any) {
  uni.navigateTo({
    url: `/pages/my/confirm/${item.value}`
  })
}
</script>

<template>
  <div class="li-user">
    <!-- <div class="my"> -->
    <div class="li-user-info">
      <div class="li-user-info-icon">
        <img class="li-user-info-icon-tx" src="/src/static/home/user.png" alt="">
        <!-- <div class="i-ri:user-line li-user-info-icon-tx" style="color: #eb0909;"></div> -->
      </div>
      <div class="li-user-info-con">
        <div class="li-user-info-con-name">{{ userName }}</div>
        <div class="li-user-info-con-role">{{ {
          '00': '商户管理员', '01': '商户员工', '02': '门店店长', '03': '门店店员', '04':
          '商户业务主管'
          }[roleFlag] }}
        </div>
      </div>
    </div>


    <!-- 操作按钮组 -->
    <div class="li-user-btns">
      <nut-grid :border="false" clickable>
        <nut-grid-item v-for="(item, index) in menu" :key="index" :text="item.name" @click="(e) => goMenu(item, e)">
          <!-- <img class="img" :src="item.icon" alt=""> -->
          <div class="li-user-btns-iBox" :style="{ backgroundColor: item.bgcolor }">
            <div :class="item.icon" class="li-user-btns-iBox-icon" :style="{ color: item.color }"></div>
          </div>
        </nut-grid-item>
      </nut-grid>
    </div>

    <div class="li-user-list">
      <nut-cell-group>
        <nut-cell title="消息推送开关">
          <template #link>
            <nut-switch v-model="push"></nut-switch>
          </template>
        </nut-cell>
      </nut-cell-group>
    </div>
    <nut-action-sheet description="请选择需要确认的渠道" v-model:visible="visible" :menu-items="menuItems" @choose="chooseItem">
    </nut-action-sheet>

  </div>
</template>

<route lang="json">{
  "layout": "home",
  "style": {
    "navigationBarTitleText": "我的",
    "backgroundColorContent": "#f1f1f1"
  }
}</route>

<style lang="sass" scoped>
.my
  padding: 10px
  .user
    display: flex
    background-color: blue
    padding: 20px 40px
    border-radius: 8px
    color: #fff
    .icon
      vertical-align: middle
      line-height: 54px
      height: 44px
      width: 44px
      border-radius: 50%
      border: 3px solid #fff
      text-align: center
      margin-right: 10px
    .info
      .name
        font-size: 24px
  .grid
    .img
      width: 25px
      height: 25px
:deep(.nut-grid-item__content)
  background: none!important
  </style>
